<template>
    <div class="bigbox">
        <div>
            <h1>添加或修改</h1>
        </div>

        <div>
            <table>
                <tbody>
                    <tr>
                        <td>书本名称：<input type="text" placeholder="请输入书本名称" v-model="data.formBook.bookName"></td>
                        <td>书本作者：<input type="text" placeholder="请输入书本作者" v-model="data.formBook.bookAuthor"></td>
                        <td>书本价格：<input type="text" placeholder="请输入书本价格" v-model="data.formBook.bookPrice"></td>
                        <td>书本数量：<input type="text" placeholder="请输入书本数量" v-model="data.formBook.bookNum"></td>
                    </tr>
                    <tr>
                        <td>
                            <input type="button" value="确认" @click="saveBtn">
                            <input type="button" value="返回" @click="cancelBtn">
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</template>

<script setup>
import axios from 'axios';
import { onMounted,reactive } from 'vue';
import { useRoute,useRouter } from 'vue-router';

const api = 'http://localhost:8000'

const router = useRouter()

const id = useRoute().params.id

const data = reactive(
    {
        formBook:{}
    }
)

//新增或修改图书
function saveBtn() {
    if (id) {
        axios.put(`${api}/book/${id}`,data.formBook).then(()=>{
            router.push({name:'book'})
        })
    } else {
        axios.post(`${api}/book`,data.formBook).then(()=>{
            router.push({name:'book'})
        })
    }
}

//根据id查询图书信息
function queryById() {
    axios.get(`${api}/book/${id}`).then((res)=>{
        data.formBook = res.data.data
    })
}

//取消操作
function cancelBtn() {
    router.push({name:'book'})
}

//组件挂载时执行
onMounted(()=>{
    if (id) {
        queryById()
    }
})


</script>

<style scoped>
/* 这里可以添加样式 */
.bigbox {
  font-family: Arial, sans-serif;
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

h1 {
  text-align: center;
}

table {
  width: 100%;
  margin-top: 20px;
}

td {
  padding: 10px;
}

input[type="text"] {
  width: 100%;
  padding: 8px;
  box-sizing: border-box;
  border: 1px solid #ccc;
  border-radius: 4px;
}

input[type="button"] {
  padding: 10px 20px;
  margin-right: 10px;
  border: none;
  border-radius: 4px;
  background-color: #4CAF50;
  color: white;
  cursor: pointer;
}

input[type="button"]:hover {
  background-color: #45a049;
}
</style>
